<template>
    <div>
        <div class="main">
            <!--      基础控件      -->
            <el-card class="atom-panel">
                <template #header>
                    <div class="card-header">
                        <div class="text-icon">
                            <span>💡</span>
                        </div>
                        <span>基础控件</span>
                    </div>
                </template>
                <draggable
                    class="cardItem"
                    :list="baseComponents"
                    @start="drag = true"
                    @end="drag = false"
                    :group="{name: 'people', pull: 'clone', put: false}"
                    :sort="false"
                    item-key="name"
                    :clone="clone"
                >
                    <template #item="{element}">
                        <el-card class="dra-card" style="cursor: move;margin: 10px">
                            <el-icon :size='14'>
                                <component :is="element.icon"/>
                            </el-icon>
                            {{ element.title }}
                        </el-card>
                    </template>
                </draggable>
            </el-card>
            <!--      表单区域      -->
            <el-card class="form-panel test-1">
                <template #header>
                    <div class="card-header">
                        <div class="text-icon">
                            <span>📑</span>
                        </div>
                        <span>表单区域</span>
                    </div>
                </template>
                <div class="tip" style="text-align: center;margin-top: 10px"
                     v-show="form.length === 0">
                    👈 请在左侧选择控件并拖至此处
                </div>
                <draggable
                    v-model="form"
                    tag="el-row"
                    @start="drag = true, choose = '0'"
                    @end="drag = false"
                    :animation="340"
                    item-key="field"
                    group="people"
                    scrollSensitivity="100"
                >
                    <template #item="{element,index}">
                        <ElComponents
                            :element="element"
                            :activeId="choose"
                            :copy="copy"
                            :delete="del"
                            :form="form"
                            :choose="chooseComponent"
                            @click.stop="chooseComponent(element)"></ElComponents>
                    </template>
                </draggable>
            </el-card>
            <!--      编辑控件      -->
            <el-card class="setting-panel">
                <template #header>
                    <div class="card-header">
                        <div class="text-icon">
                            <span>⚙️</span>
                        </div>
                        <span>编辑控件</span>
                    </div>
                </template>
                <div v-if="choose !== '0'">
                    <el-card class="dra-card cardItem" :body-style="{'height': '60vh'}" style="margin: 10px;">
                        <div>
                            <el-icon :size='16'>
                                <component :is="activeData.icon"/>
                            </el-icon>
                            {{ activeData.title }}
                        </div>
                        <div style="margin-top: 10px;">
                            <atom-config :obj="activeData"></atom-config>
                        </div>
                    </el-card>
                </div>
            </el-card>
            <operation-button :model="form" @import="importJson"></operation-button>
        </div>
    </div>
</template>
<script lang="ts">
import {defineComponent, reactive, toRefs} from 'vue'
import draggable from 'vuedraggable'
import atomConfig from '../components/home/atomConfig.vue'
import baseComponents from '../config/formsDict.js'
import ElComponents from '../components/home/atom/elComponents.jsx'
import operationButton from '../components/operationButton.vue'
import {mapMutations, mapState} from "vuex";
import * as fs from "fs";

export default defineComponent({
    components: {draggable, atomConfig, operationButton, ElComponents},
    computed: {
        ...mapState(['formData'])
    },
    setup() {
        const config = reactive({
            drag: false,
            baseComponents: baseComponents,
            activeData: {},
            form: [],
            choose: '0',
            show: false
        })

        // 选中组件
        function chooseComponent(element) {
            config.activeData = element
            config.choose = element.field
        }

        // 获取随机ticks作为id
        function getId() {
            return (Math.floor(Math.random() * (99999 - 10000)) + 10000).toString()
                + new Date().getTime().toString().substring(5);
        }

        // 删除组件
        function del(list,id) {
            let delIdx = list.findIndex(i => i.field === id)
            if (delIdx >= 0) list.splice(delIdx, 1)
            if (config.choose === id) {
                config.activeData = {}
                config.choose = '0'
            }
            if (!config.form.length) {
                config.activeData = {}
                config.choose = '0'
            }
        }

        // 复制组件
        function copy(list,node) {
            let copIndex = list.findIndex(i => i.field === node.field)
            list.splice(copIndex + 1, 0, clone(node))
        }

        // 克隆组件
        function clone(obj) {
            let cloneCp = reactive(JSON.parse(JSON.stringify(obj)));
            cloneCp.field = getId()
            return cloneCp
        }

        return {...toRefs(config), chooseComponent, getId, del, copy, clone}
    },
    beforeRouteLeave(to, from, next) {
        if (!this.form.length) {
            this.setState({formData: JSON.stringify([])})
            localStorage.setItem("formData", JSON.stringify([]));
            next(true)
            return
        }
        this.saveData(next)
    },
    created() {
        if (this.formData) {
            this.form = JSON.parse(this.formData)
        }
    },
    methods: {
        ...mapMutations(['setState']),
        saveData(next) {
            let message = '即将离开页面，是否缓存当前文档'
            this.$confirm(message, {
                confirmButtonText: '确认',
                cancelButtonText: '取消缓存'
            }).then(() => {
                this.setState({formData: JSON.stringify(this.form)})
                localStorage.setItem("formData", JSON.stringify(this.form));
                this.$message.success('缓存表单数据成功')
                next(true)
            }).catch(() => {
                this.setState({formData: JSON.stringify([])})
                localStorage.setItem("formData", JSON.stringify([]));
                next(true)
            })
        },
        // 导入JSON
        importJson(obj) {
            this.form = obj
        }
    }
})
</script>
<style lang="scss" scoped>
.cardItem {
    position: relative;
    animation: cardIn 1s;
    -webkit-animation: cardIn 1s; /* Safari and Chrome */
}

@keyframes cardIn {
    0% {
        top: -10px;
    }
    100% {
        top: 0;
    }
}

.formCard {
    min-width: 630px;
    margin: 10px;
    cursor: pointer
}

.main {
    position: absolute;
    top: 20px;
    left: 20px;
    width: calc(100% - 20px);
    height: calc(100% - 40px);
    display: flex;

    .card-header {
        text-align: center;

        .text-icon {
            &:hover {
                -webkit-animation: spin 1s linear 1s 5 alternate;
                animation: spin 1s linear infinite;
            }
        }

        @keyframes spin {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(360deg);
            }
        }
    }

    .atom-panel {
        min-width: 340px;
        height: 100%;
        border-top-left-radius: 20px;
        border-bottom-left-radius: 20px;
    }

    .form-panel {
        width: calc(100% - 820px);
        min-width: 700px;
        height: calc(100% - 30px);
        margin: 0 10px;
        padding-bottom: 30px;
    }

    .setting-panel {
        min-width: 435px;
        height: 100%;
        border-top-right-radius: 20px;
        border-bottom-right-radius: 20px;
    }
}

:deep(.el-button+.el-button) {
    margin-left: 6px;
}

:deep(.el-card__body) {
    height: calc(100% - 90px);
    overflow-y: auto;
}

:deep(.el-card__body)::-webkit-scrollbar { /*滚动条整体样式*/
    width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
    height: 8px;
}
</style>
